<template>
  <div class="role-manager">
    <!-- 角色查询  -->
    <div class="query-form">
      <el-form
        size="small"
        :inline="true"
        ref="queryForm"
        :model="queryForm"
        class="demo-form-inline"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="queryForm.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetForm('queryForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 角色列表渲染 -->
    <div class="base-table">
      <!-- 新增按钮 -->
      <div class="action">
        <el-button type="primary" size="small" @click="handleOpen()" v-has="'role-create'"
          >创建</el-button
        >
      </div>
      <!-- 角色列表 -->
      <el-table :data="roleList" size="mini" style="width: 100%" v-has="'role-query'">
        <el-table-column
          v-for="(item, index) in columns"
          :key="index"
          :formatter="item.formatter"
          :prop="item.prop"
          :label="item.label"
        >
        </el-table-column>
        <el-table-column label="操作" width="260">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)" v-has="'role-edit'"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="primary"
              @click="handleOpenPremission(scope.row)"
              v-has="'role-setting'"
              >权限设置</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row._id)"
              v-has="'role-delete'"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 角色列表分页 -->
      <el-pagination
        class="pagination"
        background
        layout="prev, pager, next"
        :current-page="queryForm.pageNum"
        :page-size="queryForm.pageSize"
        @current-change="handleCurrent"
        :total="queryForm.total"
      >
      </el-pagination>
    </div>
    <!-- 角色弹窗 -->
    <el-dialog :title="title" :visible.sync="showModal">
      <el-form :model="roleForm" ref="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="roleForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 权限设置弹窗 -->
    <el-dialog title="权限设置" :visible.sync="showPremission">
      <el-form :model="premissionForm" label-width="120px">
        <el-form-item label="角色名称">
          <span>{{ premissionRoleName }}</span>
        </el-form-item>
        <el-form-item label="选择权限">
          <el-tree
            ref="tree"
            :data="menuList"
            show-checkbox
            node-key="_id"
            :props="{label : 'menuName'}"
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPremission">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
export default {
  name: "",
  data() {
    return {
      premissionForm: {
        permissionList : {
          halfCheckedKeys : [],
          checkedKeys : []
        }
      },
      menuList : [],
      premissionRoleName: "",
      premissionId: "",
      showPremission: false,
      queryForm: {
        roleName: "",
        total: 0,
        pageNum: 1,
        pageSize: 10,
      },
      roleForm: {
        action: "",
        roleName: "",
        remark: "",
      },
      showModal: false,
      title: "",
      roleList: [],
      rules: {
        roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
      },
      columns: [
        {
          label: "角色名称",
          prop: "roleName",
        },
        {
          label: "备注",
          prop: "remark",
        },
        {
          label: "权限列表",
          prop: "",
        },
        {
          label: "更新时间",
          prop: "createTime",
          formatter(row, column, value) {
            return moment.parseZone(value).local().format("YYYY-MM-DD HH:mm:ss");
          },
        },
        {
          label: "创建时间",
          prop: "createTime",
          formatter(row, column, value) {
            return moment.parseZone(value).local().format("YYYY-MM-DD HH:mm:ss");
          },
        },
      ],
    };
  },
  created() {
    //调用初始化角色列表方法
    this.getRoleList();
    //调用初始化菜单列表数据
    this.getMenuList()
  },
  methods: {
    //初始化角色列表方法
    async getRoleList() {
      let res = await this.roleApi.getRoleList(this.queryForm);
      console.log(res);
      this.roleList = res.list;
      this.queryForm.total = res.page.total;
    },
    //初始化菜单列表数据
    async getMenuList(){
      let res = await this.menuApi.getMenuList();
      console.log("Res=>:",res)
      this.menuList = res
    },
    //角色查询
    handleQuery() {
      this.getRoleList();
      this.resetForm("queryForm");
    },
    //表单重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //打开创建弹窗方法
    handleOpen() {
      this.showModal = true;
      this.roleForm.roleName = "";
      this.roleForm.remark = "";

      this.title = "创建角色";
      this.roleForm.action = "create";
    },
    //打开编辑弹窗方法
    handleEdit(row) {
      this.showModal = true;
      this.title = "编辑角色";
      this.roleForm.action = "edit";
      this.roleForm.roleName = row.roleName;
      this.roleForm.remark = row.remark;
    },
    //分页方法
    handleCurrent(val) {
      this.queryForm.pageNum = val;
      this.getRoleList();
    },
    //提交弹窗表单的数据
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          let res = await this.roleApi.rolesOperate(this.roleForm);
          this.handleClose();
          this.getRoleList();
        } else {
          return false;
        }
      });
    },
    //关闭弹窗方法
    handleClose() {
      this.showModal = false;
    },
    //删除功能
    async handleDelete(id) {
      let res = await this.roleApi.rolesOperate({ action: "delete", _id: id });
      this.$message.success("删除成功");
      this.queryForm.pageNum = 1;
      this.getRoleList();
    },
    //打开权限设置弹窗
    handleOpenPremission(row) {
      console.log(row);
      this.showPremission = true;
      this.premissionRoleName = row.roleName;
      this.premissionId = row._id;

      let {checkedKeys} = row.permissionList;
      console.log("checkedKeys=>",checkedKeys);
      this.$nextTick(()=>{
          this.$refs["tree"].setCheckedKeys(checkedKeys);
      })
    },
    //提交选中的权限数据
    async submitPremission(){
      //1. 获取到所有选中的节点
      let nodes = this.$refs["tree"].getCheckedNodes()
      console.log(nodes)
      //2. 获取半选中的父菜单节点
      let halfKeys = this.$refs["tree"].getHalfCheckedKeys()

      //创建两个变量,分别保存所选中的子菜单数据以及半选中或者选中的父菜单数据
      let checkedKeys = [];

      let parentKeys = [];

      nodes.map(item=>{
        if(item.children){
          parentKeys.push(item._id)
        }else{
          checkedKeys.push(item._id)
        }
      })

      let params = { 
        _id : this.premissionId,
        permissionList : {
          halfCheckedKeys : parentKeys.concat(halfKeys),
          checkedKeys : checkedKeys
        }
      }

      let res = await this.roleApi.settingRolePremission(params);
      this.showPremission = false;
      this.$message.success("设置成功");
      this.getRoleList()


    }
  },

  components: {},
};

/***
 *
 *
 * 1. 点击权限设置按钮,显示dialog弹窗
 *
 * 2. 保存权限设置名称以及当前角色的id
 *  handleOpenPremission(row) {
 *    //让弹窗显示
      this.showPremission = true;
      //保存角色名称
      this.premissionRoleName = row.roleName;
      //保存当前角色的id, 因为我们提交数据的时候需要将当前所点击的角色id发送给后台
      this.premissionId = row._id;
    },
 *
 * 3. 实现权限设置弹窗布局
 *
 * 4. 实现el-tree的展示,并且拉取菜单树并通过el-tree展示
 * 
 <el-tree
            ref="tree"
            :data="menuList"
            show-checkbox
            node-key="_id"
            :props="{label : 'menuName'}"
          >
          </el-tree>
 * 5. 让拉取的权限进行选中
 * 
 * //获取到所选中的子菜单的id 数组
      let {checkedKeys} = row.permissionList;
      //通过setCheckedKeys设置选中子菜单的id 数组
      this.$nextTick(()=>{
          this.$refs["tree"].setCheckedKeys(checkedKeys);
      })
 *
 * 6. 实现提交设置权限数据的功能
 *    async submitPremission(){
      //1. 获取到所有选中的节点
      let nodes = this.$refs["tree"].getCheckedNodes()
      console.log(nodes)
      //2. 获取半选中的父菜单节点
      let halfKeys = this.$refs["tree"].getHalfCheckedKeys()

      //创建两个变量,分别保存所选中的子菜单数据以及半选中或者选中的父菜单数据
      let checkedKeys = [];

      let parentKeys = [];

      nodes.map(item=>{
        if(item.children){
          parentKeys.push(item._id)
        }else{
          checkedKeys.push(item._id)
        }
      })

      let params = { 
        _id : this.premissionId,
        permissionList : {
          halfCheckedKeys : parentKeys.concat(halfKeys),
          checkedKeys : checkedKeys
        }
      }

      let res = await this.roleApi.settingRolePremission(params);
      this.showPremission = false;
      this.$message.success("设置成功");
      this.getRoleList()


    }
 *
 * */
</script>

<style scoped></style>
